define(["jquery", "bbcare", "jqprint", "echarts",
    "scprit/department/vm/assessmentScreening/albertaAssessmentOfInfants.ui.js",
    "scprit/department/vm/assessmentScreening/assessmentScreeningQuestion.servers.js"
], function ($, $bb, $jqprint, echarts, $ui, $servers) {
    var event = {}
    var page = 1, rows = 100
    event.pageInit = function (getParams) {
        var userId = getParams.userId
        var type = getParams.type
        var answerId = getParams.answerId
        //历史记录列表：
        var hisParams = $servers.hisParams(userId, type, page, rows)
        if (window.__config__.role.indexOf('ReadOnly') > -1) {
            $('#modify').css({
                display: 'none'
            })
            $('#modifyRemark').css({
                display: 'none'
            })
        }
        var hisFn = function (data) {
            for (var i = 0; i < data.rows.length; i++) {
                data.rows[i].testAge = $servers.getAge($servers.dateDiff(data.rows[i].birthday, data.rows[i].createTime.substring(0, 10)))
            }
            $ui.historyInit({ "id": "#albertaHis", "data": data.rows })
            if (!answerId) {
                answerId = $("#albertaHis>li").eq(0).attr("answerId")
                getResult(userId, answerId, type)
                $("#albertaHis>li").eq(0).addClass("select").siblings().removeClass("select")
            } else {
                checkedFn(answerId)
                getResult(userId, answerId, type)
            }
            //历史记录列表点击事件：
            $("#albertaHis>li").click(function () {
                $(this).addClass("select").siblings().removeClass("select")
                answerId = $(this).attr("answerId")
                getResult(userId, answerId, type)
            })
            $("#modify").click(function () {
                if ($(this).attr("type") == "modify") {
                    $(".guides").attr("contentEditable", true).addClass("edit")
                    if ($("#guides").html() == "暂无指导意见") {
                        $("#guides").html("")
                    }
                    $(this).attr("type", "save").html('<i class="fa fa-check-square" aria-hidden="true"></i>确认修改')
                } else if ($(this).attr("type") == "save") {
                    $(".guides").removeAttr("contentEditable").removeClass("edit")
                    $(this).attr("type", "modify").html('<i class="fa fa-pencil-square" aria-hidden="true"></i>修改建议')
                    var guides = $.trim($("#guides").html())
                    var remark = $("#remark").length > 0 ? $.trim($("#remark").html()) : ""
                    if (!guides) {
                        $("#guides").html("暂无指导意见")
                        guides = "暂无指导意见"
                    }
                    modifyGuides(userId, answerId, guides, remark, type)
                }
            })
            $("#modifyRemark").click(function () {
                if ($(this).attr("type") == "modify") {
                    $(".remark").attr("contentEditable", true).addClass("edit")
                    if ($("#remark").html() == "暂无备注") {
                        $("#remark").html("")
                    }
                    $(this).attr("type", "save").html('<i class="fa fa-check-square" aria-hidden="true"></i>确认修改')
                } else if ($(this).attr("type") == "save") {
                    $(".remark").removeAttr("contentEditable").removeClass("edit")
                    $(this).attr("type", "modify").html('<i class="fa fa-pencil-square" aria-hidden="true"></i>修改备注')
                    var guides = $.trim($("#guides").html())
                    var remark = $.trim($("#remark").html())
                    if (!remark) {
                        $("#remarkremark").html("暂无备注")
                        remark = "暂无备注"
                    }
                    modifyGuides(userId, answerId, guides, remark, type)
                }
            })
        }
        $servers.history(hisParams, hisFn)
    }
    var getResult = function (userId, answerId, type) {
        getInfo(userId, answerId)
        getTrends(userId, answerId, type)
        getGuides(userId, type, answerId)
    }
    var checkedFn = function (answerId) {
        $("#albertaHis").find("li").each(function (i) {
            var $this = $(this)
            if ($this.attr("answerId") == answerId) {
                $(this).addClass("select").siblings().removeClass("select")
            }
        })
    }
    var getInfo = function (userId, answerId) {
        var params = $servers.reportParams(userId, answerId)
        var infoFn = function (data) {
            var dt = data.data
            var result = $.parseJSON(dt.result)
            dt.gender = dt.gender == "F" ? "女" : "男"
            dt.age = $servers.age($servers.dateDiff(dt.birthday, dt.createTime.substring(0, 10)), dt.pregnancyWeek)
            dt.actualAge = $servers.getAge($servers.dateDiff(dt.birthday, dt.createTime.substring(0, 10)))
            dt.preWindowProne = result.prone.preWindowProne
            dt.windowProne = result.prone.windowProne
            dt.preWindowDorsa = result.dorsa.preWindowDorsa
            dt.windowDorsa = result.dorsa.windowDorsa
            dt.preWindowSeats = result.seats.preWindowSeats
            dt.windowSeats = result.seats.windowSeats
            dt.preWindowStand = result.stand.preWindowStand
            dt.windowStand = result.stand.windowStand
            dt.totalScore = result.total.totalScore
            dt.percent = result.total.percent ? result.total.percent : "无"
            if (dt.percent != "无") {
                if (dt.percent.indexOf(">") != "-1") {
                    dt.className = "color-90"
                } else if (dt.percent.indexOf("~") != "-1") {
                    var lens = dt.percent.length
                    var indexUnit1 = dt.percent.indexOf("%")
                    var indexUnit2 = dt.percent.indexOf("~")
                    var firstNum = dt.percent.substring(0, indexUnit1)
                    var lastNum = dt.percent.substring(indexUnit2 + 1, lens - 1)
                    if (lastNum == 10) {
                        dt.className = "color-10"
                    } else if (firstNum >= 10 && lastNum <= 25) {
                        dt.className = "color-10-25"
                    } else if (firstNum >= 25 && lastNum <= 50) {
                        dt.className = "color-25-50"
                    } else if (firstNum >= 50 && lastNum <= 75) {
                        dt.className = "color-50-75"
                    } else if (firstNum >= 75 && lastNum <= 90) {
                        dt.className = "color-75-90"
                    }
                } else if (dt.percent.indexOf("<") != "-1") {
                    dt.className = "color-10"
                }
            }
            $ui.infoDetailInit({ "id": "#infoShow", "data": dt })
            $ui.infoDetailInit({ "id": "#printPatientInfo", "data": dt })
            $("#doctor").html(dt.doctorName + "(" + dt.hospName + "-" + dt.deptName + ")")
            $("#checkTime").html(dt.createTime)
        }
        $servers.report(params, infoFn)
    }
    var getTrends = function (userId, answerId, type) {
        var params = $servers.trendsParams(userId, answerId, type)
        var trendsFn = function (data) {
            var series = trendsDataDeal(data.data)
            trendsInit("trends", series)
        }
        $servers.trends(params, trendsFn)
    }
    var trendsInit = function (dom, series) {
        var myChart = echarts.init(document.getElementById(dom))
        // 指定图表的配置项和数据
        var option = {
            tooltip: {
                formatter: function (params, ticket, callback) {
                    var val = ""
                    if (params.data instanceof Array) {
                        val += params.seriesName + ": " + parseFloat(params.data[1]).toFixed(3)
                    } else if (params.componentType != "markPoint") {
                        var days = params.data.value[0] * 30.4
                        var age = $servers.getAge(days)
                        val += "月龄:" + age + "<br/>" + params.seriesName + ":" + parseFloat(params.data.value[1]).toFixed(2)
                    }
                    return val
                }
            },
            grid: {
                show: true,
                left: '5%',
                right: '5%',
                bottom: '3%',
                top: '4%',
                containLabel: true
            },
            xAxis: {
                type: "value",
                name: '年龄（月）',
                nameLocation: 'middle',
                nameGap: "25",
                nameTextStyle: { color: "#fff" },
                max: 19,
                min: 0,
                interval: 1,
                axisTick: {
                    show: true,
                    inside: true
                },
                axisLabel: {
                    textStyle: {
                        color: "#fff"
                    }
                }
            },
            yAxis: {
                type: 'value',
                position: "right",
                name: 'AIMS得分',
                nameLocation: 'middle',
                nameGap: "25",
                nameTextStyle: { color: "#fff" },
                max: 60,
                min: 0,
                interval: 1,
                splitArea: {
                    show: true,//保留网格区域
                    areaStyle: {
                        color: "#fff"
                    }
                },
                axisTick: {
                    inside: false,
                    show: true
                },
                axisLabel: {
                    textStyle: {
                        color: "#fff"
                    },
                    formatter: function (value, index) {
                        return value % 5 != 0 ? '' : value
                    }
                }
            },
            animation: false,
            series: series
        }
        myChart.setOption(option)
        $("#trendsImg").html('<img src="' + myChart.getDataURL({ type: "png", backgroundColor: '#aaa' }) + '" style="width: 100%;height:460px;"/>')
    }
    var recordsFn = function (data) {
        var records = {
            "nowFlag": [],
            "history": []
        }
        for (var i = 0; i < data.length; i++) {
            if (data[i].flag == 1) {
                records.nowFlag = [data[i].xDate, data[i].yDate]
            }
            var record = {
                value: [data[i].xDate, data[i].yDate],
                itemStyle: {
                    normal: {
                        color: "#9365cd"
                    },
                    emphasis: {
                        color: "#9365cd"
                    }
                }
            }
            records.history.push(record)
        }
        return records
    }
    var trendsDataDeal = function (data) {
        var series = []
        for (var item in data) {
            var name = item == "P5" ? "5%" : item == "P10" ? "10%" : item == "P25" ? "25%" : item == "P50" ? "50%" : item == "P75" ? "75%" : item == "P90" ? "90%" : "aims"
            var lineColor = item == "P5" ? "#de1313" : item == "P10" ? "#fa6a00" : item == "P25" ? "#ecc200" : item == "P50" ? "#81c106" : item == "P75" ? "#27d006" : item == "P90" ? "#0c852b" : "#9365cd"
            var lineType = item == "P5" || "P90" || "records" ? "solid" : item == "P10" || "P90" ? "dashed" : item == "P75" || "P25" ? "dotted" : ''
            if (item == "records") {
                var records = recordsFn(data[item])
                var trend = {
                    name: name,
                    type: 'line',
                    data: records.history,
                    symbol: 'circle',
                    symbolSize: '6',
                    markPoint: {
                        itemStyle: {
                            normal: {
                                color: lineColor
                            }
                        },
                        data: [
                            {
                                xAxis: records.nowFlag[0],
                                yAxis: records.nowFlag[1]
                            }
                        ]
                    },
                    itemStyle: {
                        normal: {
                            color: lineColor,
                            lineStyle: {
                                color: lineColor,
                                type: lineType,
                                width: 1
                            }
                        },
                        emphasis: {
                            color: lineColor
                        }
                    },
                    yAxisIndex: 0
                }
            } else {
                trend = {
                    name: name,
                    type: 'line',
                    smooth: "true",
                    symbol: 'circle',
                    hoverAnimation: false,
                    itemStyle: {
                        normal: {
                            color: "transparent",
                            lineStyle: {
                                color: lineColor,
                                type: lineType,
                                width: 1
                            }
                        }
                    },
                    data: data[item],
                    yAxisIndex: 0
                }
            }
            series.push(trend)
        }
        return series
    }
    var getGuides = function (userId, exam, evaId) {
        var params = $servers.getGuidesParams(userId, exam, evaId)
        var guidesFn = function (data) {
            if (data.data) {
                $("#guides,#printGuides").html(data.data.guide)
                if ($("#remark").length > 0) $("#remark").html(data.data.remark)
            } else {
                $("#guides,#printGuides").html("暂无指导意见")
                if ($("#remark").length > 0) $("#remark").html("暂无备注")
            }
        }
        $servers.getGuides(params, guidesFn)
    }
    var modifyGuides = function (userId, evaId, guides, remark, exam) {
        var params1 = $servers.modifyGuidesParams(userId, evaId, guides, remark)
        var guidesFn = function (data2) {
            getGuides(userId, exam, evaId)
        }

        $servers.modifyGuides(params1, guidesFn)

    }

    return event
})